package cn.stylefeng.guns.rabbitmq.service.impl;

import cn.stylefeng.guns.rabbitmq.config.RenStatusMsg;
import cn.stylefeng.guns.rabbitmq.model.ResultParam;
import cn.stylefeng.guns.rabbitmq.service.ICardService;
import cn.stylefeng.guns.rabbitmq.util.DES3Util;
import cn.stylefeng.guns.rabbitmq.util.EncryptionUtil;
import cn.stylefeng.guns.rabbitmq.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service("renCardService")
@Slf4j
public class RenCardServiceImpl implements ICardService {
    private static final String customerId = "3466993737";
    private static final String signKey = "9a46d4d5b5aaef48b192fce85702f7bc";
    private static final String paramKey = "9a46d4d5b5aaef48b192fce85702f7bc";
    private static final String callBackUrl = "9a46d4d5b5aaef48b192fce85702f7bc";

    @Value("${order.approveUrl}")
    private String approveUrl;

    /**
     * 发送
     *
     * @param object
     */
    @Override
    public boolean sendCardSubmit(JSONObject object) {
        log.info("人人销卡接收到数据：" + object.toJSONString() + "，开始提交数据到人人销卡");
        JSONObject order = object.getJSONObject("order");
        JSONObject orderItem = object.getJSONObject("orderItem");
        JSONObject channel = object.getJSONObject("channel");
        JSONArray channelParam = channel.getJSONArray("params");
        String httpUrl = channel.getString("apiUrl");
        Map<String, String> param = new HashMap<>();
        //先拆分固定参数
        for (Object objParam : channelParam) {
            JSONObject jsonObject = (JSONObject)objParam;
            if (!StringUtils.isEmpty(jsonObject.getString("value"))) {
                param.put(jsonObject.getString("key"), jsonObject.getString("value"));
            }
        }
        param.put("customerId", customerId);
        param.put("orderId", order.getString("orderNo"));
        param.put("amount", order.getString("quota"));
        if (!StringUtils.isEmpty(orderItem.getString("cardNo"))) {
            param.put("cardNumber", DES3Util.encryptToHex(paramKey,  orderItem.getString("cardNo")));
        }
        if (!StringUtils.isEmpty(orderItem.getString("cardPassword"))) {
            param.put("cardPassword", DES3Util.encryptToHex(paramKey,  orderItem.getString("cardPassword")));
        }
        //拼接参数顺序
        String paramMd5str = "customerId&orderId&productCode&amount&cardNumber&cardPassword&callbackURL";
        for (String key : param.keySet()) {
            paramMd5str = paramMd5str.replace(key, param.get(key));
        }
        paramMd5str = paramMd5str.concat("&" + signKey);
        try {
            String sign = EncryptionUtil.getMD5(paramMd5str).toLowerCase();
            param.put("sign", sign);
            log.info("向人人销卡提交数据：" + JSONObject.toJSONString(param));
            String resultStr = HttpUtil.sendPost(httpUrl, param, "utf-8");
            log.info("人人销卡返回：" + resultStr);
            if (!StringUtils.isEmpty(resultStr) && "000000".equals(resultStr)) {
                return true;
            } else {
                JSONObject body = new JSONObject();
                body.put("apiSign", "pmy2019app");
                body.put("approveStatus", false);
                body.put("orderNo", order.getString("orderNo"));
                body.put("itemQuota", null);
                body.put("payAmount", null);
                body.put("adminApprove", false);
                body.put("remark", RenStatusMsg.valueOf("code_"+ resultStr).getMessage());
                String result = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                JSONObject resJson = JSONObject.parseObject(result);
                if (resJson.getBoolean("success") || resJson.getIntValue("code") == 505) {
                    return true;
                }
            }
        } catch (IOException e) {
            log.error("人人销卡md5错误");
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 销卡回调处理
     *
     * @param param
     */
    @Override
    public boolean cardNotify(ResultParam param) {
        String orderId = param.getOrderId();
        String systemOrderId = param.getSystemOrderId();
        String productCode = param.getProductCode();
        String status = param.getStatus();
        String cardNumber = DES3Util.decryptFromHex(paramKey, param.getCardNumber());
        String cardPassword = DES3Util.decryptFromHex(paramKey, param.getCardPassword());
        String amount = param.getAmount();
        String successAmount = param.getSuccessAmount();
        String actualAmount = param.getActualAmount();
        String code = param.getCode();
        String sign = param.getSign();
        String memo = param.getMemo();
        String realPrice = param.getRealPrice();
        String[] signPre = new String[]{customerId, orderId, systemOrderId, productCode, status, amount, cardNumber, cardPassword, successAmount, actualAmount, code, signKey};
        String signStr = String.join("&", signPre);
        log.info("人人销卡回调：" + signStr);
        try {
            String signMy = EncryptionUtil.getMD5(signStr).toLowerCase();
            log.info("人人销卡签名比对，我方：" + signMy + ",他方：" + sign + ", 比对结果：" + signMy.equals(sign));
            if (signMy.equals(sign)) {
                if (status.equals("2") ) {//成功
                    log.info("准备发送成功");
                    JSONObject body = new JSONObject();
                    body.put("apiSign", "pmy2019app");
                    body.put("approveStatus", true);
                    body.put("orderNo", orderId);
                    body.put("itemQuota", new BigDecimal(realPrice).intValue());
                    body.put("costAmount", actualAmount);
                    body.put("remark", memo);
                    body.put("adminApprove", false);
                    String result = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                    JSONObject resJson = JSONObject.parseObject(result);
                    if (resJson.getBoolean("success")) {
                        return true;
                    }
                } else if (status.equals("3")) {//失败
                    log.info("准备发送失败");
                    JSONObject body = new JSONObject();
                    body.put("apiSign", "pmy2019app");
                    body.put("approveStatus", false);
                    body.put("orderNo", orderId);
                    body.put("itemQuota", new BigDecimal(realPrice).intValue());
                    body.put("costAmount", actualAmount);
                    body.put("remark", memo);
                    body.put("adminApprove", false);
                    String result = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                    JSONObject resJson = JSONObject.parseObject(result);
                    if (resJson.getBoolean("success")) {
                        return true;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @return
     */
    @Override
    public Object returnOk() {
        return "Y";
    }
}
